package com.kisyou.blogs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class 文章列表分页 {
    public static void main(String[] args) throws SQLException {

        List<Blog> blogList = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        int countPerPage = 3;

        Integer count = null;
        try (Connection c = DBUtil.connection()) {
            {
                String sql = "select count(*) from blogs";
                try (PreparedStatement ps = c.prepareStatement(sql)) {
                    try (ResultSet rs = ps.executeQuery()) {
                        rs.next();

                        count = rs.getInt(1);
                    }
                }
            }

            int pages = count / countPerPage;
            if (count % countPerPage != 0) {
                pages++;
            }
            System.out.printf("一共有 %d 页，请选择第几页:", pages);
            int numOfPage = scanner.nextInt();

            int limit = countPerPage;
            int offset = (numOfPage - 1) * countPerPage;
            {
                String sql = String.format("select bid, title, published_at, author from blogs order by published_at desc limit %d offset %d", limit, offset);
                try (PreparedStatement ps = c.prepareStatement(sql)) {
                    try (ResultSet rs = ps.executeQuery()) {
                        while (rs.next()) {
//                        int bid = rs.getInt(1);
                            int bid = rs.getInt("bid");
                            String title = rs.getString("title");
                            String publishedAt = rs.getString("published_at");
                            String author = rs.getString("author");

                            Blog blog = new Blog(bid, title, publishedAt, author);
                            blogList.add(blog);
                        }
                    }
                }
            }
        }

        // 具体如何展示
        System.out.printf("一共 %d 条博客\n", blogList.size());
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
    }
}